package com.zrwl.poscloud.xo.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.zrwl.poscloud.commons.config.proxy.WeixinConfig;
import com.zrwl.poscloud.commons.vo.proxy.UserInfoVO;
import com.zrwl.poscloud.xo.service.WeixinService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;


/**
 */
@Service
@Slf4j
public class WeixinServiceImpl implements WeixinService {

    @Autowired
    WeixinConfig weixinConfig;

    @Override
    public String flushAccessToken() {
        String accessToken = null;
        String ticket = null;
        String expiresIn = null;
        String url = "https://api.weixin.qq.com/cgi-bin/token?"
                + "grant_type=client_credential&appid=" + weixinConfig.appId
                + "&secret=" + weixinConfig.secret;
        try {
            URL urlGet = new URL(url);
            HttpURLConnection http = (HttpURLConnection) urlGet
                    .openConnection();
            http.setRequestMethod("GET"); // 必须是get方式请求
            http.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);
            http.connect();
            InputStream is = http.getInputStream();
            int size = is.available();
            byte[] jsonBytes = new byte[size];
            is.read(jsonBytes);
            String message = new String(jsonBytes, "UTF-8");
            JSONObject demoJson = JSONObject.parseObject(message);
            accessToken = demoJson.getString("access_token");
            if (accessToken == null) {
                throw new RuntimeException(message);
            }
            expiresIn = demoJson.getString("expires_in") + "000"; // 转换为毫秒
            log.info("accessToken====" + accessToken);
            WeixinConfig.accessToken = accessToken;
        } catch (Exception ex) {
            log.info("刷新 accessToken异常");
            log.error("刷新 accessToken异常" + ex.getMessage());
            ex.printStackTrace();
        }
        url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?"
                + "access_token=" + accessToken
                + "&type=jsapi";
        try {
            URL urlGet = new URL(url);
            HttpURLConnection http = (HttpURLConnection) urlGet
                    .openConnection();
            http.setRequestMethod("GET"); // 必须是get方式请求
            http.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);
            http.connect();
            InputStream is = http.getInputStream();
            int size = is.available();
            byte[] jsonBytes = new byte[size];
            is.read(jsonBytes);
            String message = new String(jsonBytes, "UTF-8");
            JSONObject demoJson = JSONObject.parseObject(message);
            ticket = demoJson.getString("ticket");
            log.info("ticket====" + ticket);
            WeixinConfig.jsapiTicket = ticket;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return WeixinConfig.accessToken;
    }

    @Override
    public String getAccessToken() {
        return WeixinConfig.accessToken;
    }

    @Override
    public UserInfoVO getOpenId(String code) {
        UserInfoVO vo = new UserInfoVO();
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?"
                + "appid=" + weixinConfig.appId
                + "&secret=" + weixinConfig.secret
                + "&code=" + code
                + "&grant_type=authorization_code";
        try {
            URL urlGet = new URL(url);
            HttpURLConnection http = (HttpURLConnection) urlGet
                    .openConnection();
            http.setRequestMethod("GET"); // 必须是get方式请求
            http.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);
            http.connect();
            InputStream is = http.getInputStream();
            int size = is.available();
            byte[] jsonBytes = new byte[size];
            is.read(jsonBytes);
            String message = new String(jsonBytes, "UTF-8");
            log.info("微信getOpenId返回====" + message);
            JSONObject demoJson = JSONObject.parseObject(message);
            try {
                vo.setAccessToken(demoJson.getString("access_token"));
                vo.setOpenId(demoJson.getString("openid"));
                vo.setErrcode(demoJson.getString("errcode"));
                vo.setErrmsg(demoJson.getString("errmsg"));
            } catch (Exception e) {
                log.error("微信getOpenId异常" + e.getMessage());
                e.printStackTrace();
                vo.setErrcode(demoJson.getString("errcode"));
                vo.setErrmsg(demoJson.getString("errmsg"));
            }
            return vo;
        } catch (Exception ex) {
            log.error("微信getOpenId异常" + ex.getMessage());
            ex.printStackTrace();
            return vo;
        }
    }

    @Override
    public UserInfoVO getUserInfo(String openId, String accessToken) {
        UserInfoVO vo = new UserInfoVO();
        String url = "https://api.weixin.qq.com/sns/userinfo?"
                + "access_token=" + accessToken
                + "&openid=" + openId
                + "&lang=zh_CN";
        try {
            URL urlGet = new URL(url);
            HttpURLConnection http = (HttpURLConnection) urlGet
                    .openConnection();
            http.setRequestMethod("GET"); // 必须是get方式请求
            http.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);
            http.connect();
            InputStream is = http.getInputStream();
            int size = is.available();
            byte[] jsonBytes = new byte[size];
            is.read(jsonBytes);
            String message = new String(jsonBytes, "UTF-8");
            log.info("微信getUserInfo返回====" + message);
            JSONObject demoJson = JSONObject.parseObject(message);
            try {
                vo.setOpenId(demoJson.getString("openid"));
                vo.setNickName(demoJson.getString("nickname"));
                vo.setSex(demoJson.getString("sex"));
                vo.setProvince(demoJson.getString("province"));
                vo.setCity(demoJson.getString("city"));
                vo.setCountry(demoJson.getString("country"));
                vo.setHeadImgurl(demoJson.getString("headimgurl"));
                vo.setPrivilege(demoJson.getString("privilege"));
                vo.setUnionId(demoJson.getString("unionid"));
                vo.setErrcode(demoJson.getString("errcode"));
                vo.setErrmsg(demoJson.getString("errmsg"));
            } catch (Exception e) {
                log.error("微信getUserInfo返回异常" + e.getMessage());
                e.printStackTrace();
                vo.setErrcode(demoJson.getString("errcode"));
                vo.setErrmsg(demoJson.getString("errmsg"));
            }
            return vo;

        } catch (Exception ex) {
            log.error("微信getUserInfo异常" + ex.getMessage());
            ex.printStackTrace();
            return vo;
        }
    }
}
